// 配置API接口地址
// const baseUrl = 'http://www.kuitao8.com/';


import SHA256 from 'crypto-js/sha256'

// 引入 弹窗组件
var modal = weex.requireModule('modal');
// 引入 请求数据组件
var stream = weex.requireModule('stream');
// 身份验证
//import jwtdecode from 'jwt-simple';

// 自定义判断元素类型JS
function toType(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

// 参数过滤函数
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}

// 工具方法
function toParams(obj) {
  var param = ""
  for (const name in obj) {
    if (typeof obj[name] != 'function') {
      param += "&" + name + "=" + encodeURI(obj[name])
    }
  }
  return param.substring(1)
};

function uncompile(code) {
  code = decodeURI(code);
  var c = String.fromCharCode(code.charCodeAt(0) - code.length);
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
  }
  return c;
}

/**
 * 接口处理函数
 */
function apiStream(method, url, params, successCallback, errorCallback) {
  // 过滤参数
  if (params) {
    params = filterNull(params)
  }

  params.httpparams101 = Math.random().toString(36).substr(2);
  let key = '%C2%81%C3%9C%C3%A1%C3%99%C2%99%C2%A5%C3%B1%C3%B3%C2%9BK%5Eggg%C2%99%C3%8A%C3%8A%C3%8A%C3%97%C2%94KMZoq';
  params.httpparams102 = SHA256(params.httpparams101 + uncompile(key)).toString();

  /*** stream ***/
  if (method === 'GET') {
    // GET 方法
    stream.fetch({
      method: 'GET',
      type: 'json',
      url: url + '?' + toParams(params),
      headers: {Authorization: 'Basic aHRtbC1jbGllbnQtMDAxLSNAITpodG1sLWNsaWVudC0wMDEtI0Ah'}
    }, function (res) {
      if (res.ok) {
        // 解密
        // let currentData = jwtdecode.decode(res.data, 'michahzdee2016', 'HS256');
        // successCallback(currentData);
        successCallback(res.data);
      } else {
        modal.toast({
          message: '请求失败,请检查网络!',
          duration: 2
        })
      }
    })
  } else if (method === 'POST') {
    // POST 方法
    stream.fetch({
      method: 'POST',
      type: 'text',
      url: url,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: 'Basic aHRtbC1jbGllbnQtMDAxLSNAITpodG1sLWNsaWVudC0wMDEtI0Ah'
      },
      body: toParams(params)
    }, function (res) {
      if (res.ok) {
        // 解密
        //let currentData = jwtdecode.decode(res.data, 'michahzdee2016', 'HS256');
        //successCallback(currentData);
        successCallback(res.data)
      } else {
        modal.toast({
          message: '请求失败,请检查网络!',
          duration: 2
        })
      }
    }, function (progress) {
      //
    })
  }
};


module.exports = {
  get: function (url, params, successCallback, errorCallback) {
    apiStream('GET', url, params, successCallback, errorCallback)
  },
  post: function (url, params, successCallback, errorCallback) {
    apiStream('POST', url, params, successCallback, errorCallback)
  }
};


